/*
 * Copyright (c) 2020-2021. the original authors and DEPSEA.ORG
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.depsea.log.config;

import org.aopalliance.aop.Advice;
import org.depsea.log.aop.advice.MethodAdvice;
import org.depsea.log.aop.advice.RequestAdvice;
import org.depsea.log.getter.impl.Swagger2ApiNameGetterImpl;
import org.depsea.log.handler.impl.ElasticsearchRequestPointHandler;
import org.depsea.log.handler.impl.RequestLogHandler;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.cloud.sleuth.Tracer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author jaune
 * @since 1.0.0
 */
@Configuration
public class ApplicationConfiguration {

    @Bean
    public Advisor requestAdvisor(Advice requestAdvice) {
        var pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("execution(* org.depsea..*.controller.*.*(..))");
        return new DefaultPointcutAdvisor(pointcut, requestAdvice);
    }

    @Bean
    public Advice requestAdvice(Tracer tracer) {
        var requestAdvice = new RequestAdvice();
        requestAdvice.setTracer(tracer);
        requestAdvice.setApiNameGetter(new Swagger2ApiNameGetterImpl());
        requestAdvice.addPointHandlers(new RequestLogHandler(), new ElasticsearchRequestPointHandler());
        return requestAdvice;
    }

    @Bean
    public Advisor appMethodAdvisor(MethodAdvice appMethodAdvice) {
        var pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression("within(org.depsea.log.module..*) || execution(* org.depsea.log.utils.*.*(..))");
        return new DefaultPointcutAdvisor(pointcut, appMethodAdvice);
    }

    @Bean
    public MethodAdvice appMethodAdvice(Tracer tracer) {
        return new MethodAdvice();
    }
}
